import React, { useState, useEffect, ReactNode } from "react"


interface PropsScrollView {
    "className": string
    /**
     * 偏移量 默认0 滑动到底部触发监听，如果设置60 则距离底部60px则触发监听
     */
    "offset"?: number

    onLoadMoreListener(): void
    children: ReactNode
}

export default function ScrollView({ className, offset = 0, onLoadMoreListener, children }: PropsScrollView) {
    const [duplicationStatus, setDuplicationStatus] = useState(false)// 防重标记
     
    const handleScrollEvent = (e: React.UIEvent<HTMLElement, UIEvent>) => {
        const { scrollTop, clientHeight, scrollHeight } = e.target as HTMLElement
        /**
         * 1. 滑动到底部
         * 2. 防重标记
         */
        if (scrollTop + clientHeight >= scrollHeight - offset && !duplicationStatus) {
            setDuplicationStatus(true)
            onLoadMoreListener()
        }
    }
    useEffect(()=>{
        setDuplicationStatus(false)
    })
    return (
        <div className={className} onScroll={handleScrollEvent}>
            {children}
        </div>
    )
}